package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

import static cn.hutool.jwt.JWTUtil.parseToken;

@RequiredArgsConstructor
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    //注解过来不需要的路径(构造函数进行注入)
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;

    //路径匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        //判断是否需要登录拦截
        RequestPath path = request.getPath();
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);//放行
        }
        //获取token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");
        if(headers !=null && !headers.isEmpty()){
            token=headers.get(0);
        }
        //检验token
        Long userId=null;
        try{
             userId= jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            //拦截，没有解析到token，响应状态码设置为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();//拦截器终止
        }
        //传递用户信息
//        System.out.println("获取到用户ID:"+userId);
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        //放行新的exchange
        return chain.filter(swe);
    }

    /**
     * 判断是不是不需要的路径，进行放行
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for(String pathPattern:excludePaths){
            if(antPathMatcher.match(pathPattern,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
